package cn.llk.mall.controller.api;

import java.time.LocalDate;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.llk.mall.entity.UserEntity;
import cn.llk.mall.service.UserService;
import cn.llk.mall.util.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author llk
 * @since 2021-04-20
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/register")
    public HttpResult<?> register(@RequestBody UserEntity user, Model model, HttpServletRequest request) {
        UserEntity dbUser = userService.getByName(user.getUserName());
        if (ObjectUtil.isNotNull(dbUser)) { // 注册
            model.addAttribute("errMsg", "用户名已经存在！");
            return HttpResult.error("用户名已经存在");
        } else {
            dbUser = new UserEntity();
            dbUser.setUserName(user.getUserName());
            dbUser.setUserPwd(user.getUserPwd());
            dbUser.setCreateDate(LocalDate.now());
            dbUser.setUpdateDate(LocalDate.now());
            userService.save(dbUser);

            // 保存到session中
            request.getSession().setAttribute("user", dbUser);
            model.addAttribute("user", dbUser);
        }
        return HttpResult.ok(dbUser, "注册成功");
    }

    @PostMapping("/login")
    public HttpResult<?> login(@RequestBody UserEntity user, Model model, HttpServletRequest request) {
        UserEntity dbUser = userService.getByName(user.getUserName());
        if (ObjectUtil.isNull(dbUser)) {  // 用户不存在
            model.addAttribute("errMsg", "用户名不存在！");
            return HttpResult.error("用户名不存在");
        }
        if (!StrUtil.equals(dbUser.getUserPwd(), user.getUserPwd())) { // 密码不正确
            model.addAttribute("errMsg", "密码错误！");
            return HttpResult.error("用户密码错误");
        } else { // 登录成功
            request.getSession().setAttribute("user", dbUser);
            model.addAttribute("user", dbUser);
            return HttpResult.ok(dbUser, "登录成功");
        }
    }
}

